package edu.the.last.fft;

/**
 * 
 * @author albertcsani
 * 
 */

public class MusicalSound {
	private double sounds[][] = new double[12][5];
//	private String[] musicSounds = { "a", "a#", "h", "c", "c#", "d", "d#", "e", " f", "f#", "g", "g#" };

	/**
	 * constructor, generates the table of sounds
	 */
	public MusicalSound() {
		sounds[0][3] = 440;
		sounds[1][3] = 466;
		sounds[2][3] = 494;
		sounds[3][3] = 523;
		sounds[4][3] = 554;
		sounds[5][3] = 587;
		sounds[6][3] = 622;
		sounds[7][3] = 659;
		sounds[8][3] = 698;
		sounds[9][3] = 740;
		sounds[10][3] = 784;
		sounds[11][3] = 831;
		for (int i = 1; i <= 3; i++) {
			for (int j = 0; j < 12; j++) {
				sounds[j][3 - i] = sounds[j][3 - i + 1] / 2;
			}
		}
		for (int j = 0; j < 12; j++) {
			sounds[j][4] = sounds[j][3] * 2;
		}
	}

	/**
	 * returns the nearest musical note to the given frequency interval
	 * 
	 * @param frequancy
	 *            the upper boundary of the frequency interval
	 * @param delta
	 *            the volume of the interval
	 * @return  int 0-12 sound, -1 nothing
	 */
	public int getSound(double frequancy, double delta) {
		if (frequancy == 0.0)
			return  -1;
		int ind = Integer.MAX_VALUE;
		for (int j = 0; j < 5; j++) {
			for (int i = 0; i < 12; i++) {
				if (ind == Integer.MAX_VALUE && sounds[i][j] > frequancy - delta) {
					if (i != 0) {
						if ((sounds[i][j] - (frequancy - delta)) < ((frequancy - delta) - (sounds[i - 1][j]))) {
							ind = i;
						} else {
							ind = i - 1;
						}
					} else {
						if ((sounds[i][j] - (frequancy - delta)) < ((frequancy - delta) - (sounds[11][j - 1]))) {
							ind = i;
						} else {
							ind = 11;
						}
					}
				}
			}
		}
		if (ind < 12) {
			return ind;
		} else {
			return -1;
		}
	}
}
